// pages/homePage/homePage.js
import request from '../../utils/request'
import {
  getCartTotalPrice
} from '../../utils/cartUtil'
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeKey: 0,
    categoryName: [],
    dishsInfo: [],
    category: [],
    showVanActionSheet: false,
    shoppingCartList: [],
    cartTotalPrice: 0, // 购物车总价
  },
  async click(event) {
    const activeKey = event.detail; // 获取当前选中的索引
    const category = this.data.categoryName[activeKey]
    const categoryId = this.data.category.find(item => item.name === category).id
    const categoryType = this.data.category.find(item => item.name === category).type
    // const res= await request({
    //   url:`/user/dish/list?categoryId=${categoryId}`
    // })
    let res = null
    if (categoryType == 1) {
      res = await request({
        url: `/user/dish/list?categoryId=${categoryId}`
      })
    } else {
      res = await request({
        url: `/user/setmeal/list?categoryId=${categoryId}`
      })
    }
    // console.log(res.result);
    this.setData({
      dishsInfo: res.result
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.footChoose = this.selectComponent("#footChoose")
    this.setmealShow = this.selectComponent("#setmealShow")
  },
  // 点击“+”按钮：打开规格弹窗
  async openSpecDialog(e) {
    const currentDish = e.currentTarget.dataset.dish;
    // console.log(currentDish);
    // 获取当前点击的菜品
    if (currentDish.hasOwnProperty('flavors')) {
      this.footChoose.showDialog(currentDish);
      // 没有flavors显示的使用以下发请求
      if (currentDish.flavors === null) {
        const res = await request({
          url: '/user/shoppingCart/add',
          method: "post",
          data: {
            "dishId": currentDish.id
          }
        })
        // 刷新商品总价
        const total = await getCartTotalPrice()
        this.setData({
          cartTotalPrice: total
        })
      }
    } // 调用组件方法显示弹窗
    else {
      const {
        result
      } = await request({
        url: `/user/setmealDish/dish/${currentDish.id}`
      })
      this.setmealShow.showDialog(result, currentDish.name)
    }
  },
  // 接收组件返回的选择结果
  async onSpecConfirm(e) {
    const {
      dish,
      selectedSpec,
      flavor
    } = e.detail;
    console.log("选择结果：", {
      菜品名称: dish.name,
      选择规格: selectedSpec,
      单价: dish.price,
      ID: dish.id,
      flavor: flavor
    });
    // 这里可以添加后续逻辑（如加入购物车）
    await request({
      url: "/user/shoppingCart/add",
      method: 'post',
      data: {
        "dishId": dish.id,
        "dishFlavor": flavor
      }
    })
    // 刷新价格
    const total = await getCartTotalPrice()
    this.setData({
      cartTotalPrice: total
    })
  },
  async setmealConfirm(e) {
    const {
      currentSetmealName
    } = e.detail
    const setmealInfo = this.data.dishsInfo.find(item => item.name === currentSetmealName)
    await request({
      url: "/user/shoppingCart/add",
      method: 'post',
      data: {
        "setmealId": setmealInfo.id
      }
    })
    // 刷新价格
    const total = await getCartTotalPrice()
    this.setData({
      cartTotalPrice: total
    })
  },
  // 展示van-action-sheet
  async changeVanActionSheet() {
    const {
      result
    } = await request({
      url: "/user/shoppingCart/list"
    })

    this.setData({
      shoppingCartList: result,
      showVanActionSheet: true
    })
  },
  onClose() {

    this.setData({
      showVanActionSheet: false
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    // 请求分类
    const res = await request({
      url: '/user/category/list'
    })
    this.setData({
      categoryName: res.result.filter(item => item.status === 1).map(item => item.name),
      category: res.result
    })
    // 请求该分类菜品
    const res2 = await request({
      url: `/user/dish/list?categoryId=${res.result[0].id}`
    })
    // 请求商品总价
    const total = await getCartTotalPrice()
    this.setData({
      dishsInfo: res2.result,
      cartTotalPrice: total
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 商品数量改变
  async onVanStepperChange(event) {
    // console.log(event.detail);
    // console.log(event.currentTarget.dataset.id);
    await request({
      url: '/user/shoppingCart/changeNumber',
      method: 'post',
      data: {
        id: event.currentTarget.dataset.id,
        number: event.detail
      }
    })
    // 再次请求购物车列表和总价
    const {
      result
    } = await request({
      url: '/user/shoppingCart/list'
    })
    const total = await getCartTotalPrice()
    this.setData({
      cartTotalPrice: total,
      shoppingCartList: result
    })
  },
  async onDeleteShop(e) {
    console.log(1);
    Dialog.confirm({
      title: '温馨提示',
      message: `确认要删除${e.currentTarget.dataset.name}商品吗?`
    }).then(async () => {
      await request({
        url: '/user/shoppingCart/delete',
        method: 'delete',
        data: {
          id: e.currentTarget.dataset.id
        }
      })
      const {
        result
      } = await request({
        url: '/user/shoppingCart/list'
      })
      const total = await getCartTotalPrice()
      this.setData({
        cartTotalPrice: total,
        shoppingCartList: result
      })

      // 重新请求购物车和总价

    })
  },
  // 清空购物车
  onClearCart(){
    Dialog.confirm({
      title: '温馨提示',
      message: `确认要清除购物车所有商品吗?`
    }).then(async () => {
      await request({
        url: '/user/shoppingCart/clear',
        method: 'delete',
      })
      const {
        result
      } = await request({
        url: '/user/shoppingCart/list'
      })
      const total = await getCartTotalPrice()
      this.setData({
        cartTotalPrice: total,
        shoppingCartList: result
      })
      // 重新请求购物车和总价
    }).catch(() => {
    })
  },
  toMyPage(){
    wx.navigateTo({
      url: '/pages/my/my',
    })
  },
  onSubmitOrder(){
    wx.navigateTo({
      url: '/pages/order/order',
    })
  }
})